package com.miraclesea.module.rbac.test;

import java.util.ArrayList;
import java.util.List;

import org.joda.time.DateTime;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import com.miraclesea.module.rbac.entity.Role;
import com.miraclesea.module.rbac.vo.Permission;

public final class RoleBuilder {
	
	public static final String ID = "ID_%s";
	public static final String NAME = "RoleName_%s";
	public static final String ASSIGNED_PERMISSION_NAME = "AssignedPermission_%d_%s";
	public static final String DENIED_PERMISSION_NAME = "DeniedPermission_%d_%s";
	
	private RoleBuilder() { }
	
	public static Role createRole(final String appendix, final int assignedPermissionCount, final int deniedPermissionCount) {
		Role result = new Role();
		result.setId(String.format(ID, appendix));
		result.setName(String.format(NAME, appendix));
		result.setCreatedDate(new DateTime(0L));
		result.setLastModifiedDate(new DateTime(0L));
		result.assignPermissions(createPermissions(ASSIGNED_PERMISSION_NAME, appendix, assignedPermissionCount));
		result.denyPermissions(createPermissions(DENIED_PERMISSION_NAME, appendix, deniedPermissionCount));
		return result;
	}

	private static List<Permission> createPermissions(final String namePrefix, final String nameAppendix, final int permissionCount) {
		List<Permission> result = new ArrayList<>(permissionCount);
		for (int i = 0; i < permissionCount; i++) {
			final int current = i;
			Permission assignedPermission = new Permission() {

				@Override
				public String toPermissionString() {
					return String.format(namePrefix, current, nameAppendix);
				}
				
			};
			result.add(assignedPermission);
		}
		return result;
	}
	
	public static Page<Role> createPage(final int size, final int number, final long total, final int assignedPermissionCount, final int deniedPermissionCount) {
		List<Role> roles = new ArrayList<>(size);
		for (int i = 0; i < size; i++) {
			roles.add(createRole(i + "", assignedPermissionCount, deniedPermissionCount));
		}
		return new PageImpl<Role>(roles, new PageRequest(number, size), total);
	}
}
